package mtn.bowen.yan.server.controller;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.AreaChart;
import javafx.scene.control.Alert;
import javafx.scene.control.TabPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import mtn.bowen.yan.server.enums.DishesKindEnum;
import mtn.bowen.yan.server.enums.DishesTypeEnum;
import mtn.bowen.yan.server.enums.WeekEnum;
import mtn.bowen.yan.server.fx.FxmlView;
import mtn.bowen.yan.server.fx.StageManager;
import mtn.bowen.yan.server.model.VarietyDishes;
import mtn.bowen.yan.server.model.WeekRecipe;
import mtn.bowen.yan.server.service.MenuManagementService;
import mtn.bowen.yan.server.service.VarietyDishesService;
import mtn.bowen.yan.server.service.WeekRecipeService;
import mtn.bowen.yan.server.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URL;
import java.util.*;

/**
 * @author <a href=mailto:yanbowen90@foxmail.com> bowen.yan </a>
 * @version 1.0
 * @description: 管理食谱
 * @date 2021-10-22 7:33 PM
 */
@Component
public class RecipeManagementController extends BaseController implements Initializable {

    private final static Logger LOGGER = LoggerFactory.getLogger(RecipeManagementController.class);

    @Resource
    private VarietyDishesService dishesService;

    @FXML
    private AreaChart<String, Number> areaChart;

    /**
     * 三餐选择
     */
    @FXML
    private JFXComboBox threeMealsComboBox;

    /**
     * 星期选择
     */
    @FXML
    private JFXComboBox recipeWeekComboBox;

    @FXML
    private TabPane kinds;

    @FXML
    private JFXButton editorKind;

    @FXML
    private StackPane stackPane;

    @Resource
    private EditorKindController editor;

    @Resource
    private MainController mainController;

    @Resource
    private WeekRecipeService weekRecipeService;

    @Resource
    private VarietyDishesService varietyDishesService;

    @Resource
    private MenuManagementService menuManagementService;

    @SuppressWarnings("unchecked")
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        try {
            //选择星期
            WeekEnum week = WeekEnum.getWeek(StageManager.getTypeAndWeekMap("Week"));
            //选择类型
            DishesTypeEnum type = DishesTypeEnum.getDishesType(StageManager.getTypeAndWeekMap("Type"));

            //选择星期
            recipeWeekComboBox.getSelectionModel().select(week.getCode() - 1);
            //选择类型
            threeMealsComboBox.getSelectionModel().select(type.getCode() - 1);

            //宽度绑定为Pane宽度
            kinds.prefWidthProperty().bind(stackPane.widthProperty());
            //设置菜品图片展示
            dishesService.setTabPane(kinds, type, week);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RecipeManagementController.initialize is error:", e);
        }
    }

    @FXML
    private void editorKind() {

        // 打开新的场景需要UI更新线程执行
        Platform.runLater(() -> {

            Stage saveEditorDiary = StageManager.getStage("saveEditorDiary");
            //食谱种类记录
            int indexKind = threeMealsComboBox.getSelectionModel().getSelectedIndex();
            String type = DishesTypeEnum.getDishesType(indexKind + 1).getMsg();
            StageManager.putTypeAndWeekMap("Type", type);
            //星期记录
            int indexWeek = recipeWeekComboBox.getSelectionModel().getSelectedIndex();
            String week = WeekEnum.getWeek(indexWeek + 1).getMsg();
            StageManager.putTypeAndWeekMap("Week", week);

            // 每次创建场景前，判断该场景是否被创建过，创建过直接显示场景即可，无需多次创建，但是需要清除上次输入的数据
            if (Objects.isNull(saveEditorDiary)) {
                try {
                    Stage stage = SpringUtils.getBean(StageManager.class).showPopWindowOnTop(FxmlView.MODULE_EDITOR_KIND);
                    // 存放Scene
                    StageManager.put("saveEditorDiary", stage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                editor.build();
                saveEditorDiary.show();
            }
            //隐藏父界面
            StackPane root = StageManager.getParentStackPaneMap("parentStackPane");
            root.setVisible(false);
        });
    }

    @FXML
    private void threeMealsComboBox() {
        //食谱种类记录
        int indexType = threeMealsComboBox.getSelectionModel().getSelectedIndex();
        String type = DishesTypeEnum.getDishesType(indexType + 1).getMsg();
        StageManager.putTypeAndWeekMap("Type", type);
        System.out.println(new Gson().toJson(StageManager.getTypeAndWeekMap("Type")));
        Map<String, WeekRecipe> map = StageManager.getAddWeekRecipeMap();
        map.clear();
        //刷新页面
        mainController.mainRecipeManagement();
    }

    @FXML
    private void weekChoiceComboBox() {
        //食谱星期记录
        int indexWeek = recipeWeekComboBox.getSelectionModel().getSelectedIndex();
        String week = WeekEnum.getWeek(indexWeek + 1).getMsg();
        StageManager.putTypeAndWeekMap("Week", week);
        System.out.println(new Gson().toJson(StageManager.getTypeAndWeekMap("Week")));
        StageManager.getAddWeekRecipeMap().clear();
        //刷新页面
        mainController.mainRecipeManagement();
    }

    @FXML
    private void weekRecipeSubmit() {
        //食谱种类记录
        int indexType = threeMealsComboBox.getSelectionModel().getSelectedIndex();
        //食谱星期记录
        int indexWeek = recipeWeekComboBox.getSelectionModel().getSelectedIndex();
        //规定
        List<VarietyDishes> dishesByTypeAndWeek = varietyDishesService.getDishesByTypeAndWeek(indexType + 1, indexWeek + 1);
        //用户输入
        Map<String, WeekRecipe> addWeekRecipeMap = StageManager.getAddWeekRecipeMap();
        if (addWeekRecipeMap.size() == 0) {
            return;
        }
        Map<Integer, Integer> inputHashMap = Maps.newHashMap();
        addWeekRecipeMap.forEach((key, value) -> {
            if (inputHashMap.containsKey(value.getKind())) {
                int temp = inputHashMap.get(value.getKind()) + 1;
                inputHashMap.put(value.getKind(), temp);
            } else {
                inputHashMap.put(value.getKind(), 1);
            }
        });

        boolean flag = false;
        for (VarietyDishes list : dishesByTypeAndWeek) {
            if (inputHashMap.containsKey(list.getKind())) {
                if (!inputHashMap.get(list.getKind()).equals(list.getQuantity())) {
                    DishesKindEnum dishesKind = DishesKindEnum.getDishesKind(list.getKind());
                    menuManagementService.showDialog("修改食谱错误", "【" + dishesKind.getMsg() + "】" + "的数量应是" + "【" + list.getQuantity() + "】", Alert.AlertType.ERROR);
                    StageManager.getAddWeekRecipeMap().clear();
                    mainController.mainRecipeManagement();
                    flag = true;
                    break;
                }
            }
        }
        if (flag) {
            return;
        }
        System.out.println("------------------------------");
        //删除数据
        addWeekRecipeMap.forEach((key, value) -> {
            weekRecipeService.deleteByWeekAndTypeAndKind(indexWeek + 1, indexType + 1, value.getKind());
        });
        //存储数据
        addWeekRecipeMap.forEach((key, value) -> {
            weekRecipeService.insertWeekRecipe(value);
        });
        StageManager.getAddWeekRecipeMap().clear();
        mainController.mainRecipeManagement();
//        menuManagementService.showDialog("食谱管理", "【修改食谱成功！】", Alert.AlertType.INFORMATION);
    }
}

